#include "socket.hpp"
#include <memory>
#include <iso646.h>
#include <iostream>
#include <fstream>
#include "httpServer.hpp"
#include <thread>
#include "HttpProtocol.hpp"
#include <cmath>
using namespace Protocol;





std::string  task (std::string &in)
{
    //这里做http响应时，应该考虑读取过来的内容，是否读取完整
    HttpRequest req;
    req.Deserialize(in);
    req.Parse();
    req.DebugHttp();
    std::string content =req.GetUrlContent();
    int code = 200;
    if(content.empty())
    {
        code = 404;
        content = req.Get404();
    }


    HttpResponse resp;
    resp.SetCode(code);
    resp.SetCode_Desc(Status_code_Desc::Code_desc(code));
    resp.make();
    std::string ContentLength = "Content-Length: " + std::to_string(content.size())+"\r\n";
    resp.AddHeader(ContentLength);
    std::string Contenttype= "Content-Type: " + Contentmap::sub_type(req.Subffix()) + "\r\n";
    resp.AddHeader(Contenttype);

    //重定向测试
    // std::string Location = "Location: https://ys.mihoyo.com/cloud/#/" + HttpSep;
    // resp.AddHeader(Location);

    resp.AddContent(content);
    std::string DebugTest = resp.serialize();
    return resp.serialize();
}



int main(int argc,char* argv[])
{
    Status_code_Desc::Init();
    Contentmap::Init();
    if(argc != 2)
    {
        std::cout<<"Usage ./"<<argv[0]<<" port\n";
        return 0; 
    } 
    uint16_t localport = std::stoi(argv[1]);


    std::unique_ptr<httpServer> svr(new httpServer(localport,task));
    svr->WorkLoop();
    return 0;
}